package com.seer.seertest.filter;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.PostConstruct;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class JwtFilter extends OncePerRequestFilter {

    private static final List<String> WHITE_LIST = new ArrayList<>(Arrays.asList(
            "/api/sign-in"
    ));

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return WHITE_LIST.contains(request.getRequestURI());
    }

    @Value("${security.jwt.secret-key}")
    private String secretKey; // 从配置读取密钥

    @PostConstruct
    public void init() {
        logger.info("正在加载的密钥值:"+ secretKey); // 查看实际注入值
        if (secretKey == null) {
            logger.error("❌ 密钥未成功注入，请检查配置！");
        } else {
            logger.info("✅ JWT 密钥已加载，长度: " + secretKey.length());
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            String token = resolveToken(request);
            if (token == null || !validateToken(token)) {
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid or missing token");
                return; // 关键：终止过滤器链
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Authentication failed");
        }
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    private boolean validateToken(String token) {
        if (secretKey == null) { // 新增判空保护
            logger.error("‼️ 密钥未初始化，请检查配置！");
            return false;
        }
        try {
            byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); // 显式编码转换
            Jwts.parserBuilder()
                    .setSigningKey(keyBytes)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            logger.error("Token已过期:"+e.getMessage());
        } catch (Exception e) { // 捕获更广泛的异常
            logger.error("JWT验证失败:"+ e);
        }
        return false;
    }
}








